<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            clearable
            @clear="getUserList"
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
          >
            <el-button
              slot="append"
              @click="getUserList"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="AdddialogVisible = true" type="success"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userlist" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="180">
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="role_name" label="权限"> </el-table-column>
        <el-table-column prop="mg_state" label="权限">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="showEditdialog(scope.row.id)"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              type="danger"
              @click="RemoveUser(scope.row.id)"
              icon="el-icon-delete"
              circle
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
            >
              <el-button
                @click="setRole(scope.row)"
                type="warning"
                icon="el-icon-s-tools"
                circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      width="50%"
      title="添加用户"
      :visible.sync="AdddialogVisible"
      @close="Adddialogcloesd"
    >
      <!-- 主体 -->
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFrom.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 这是底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="AdddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AdddUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      width="50%"
      title="修改用户"
      :visible.sync="EditdialogVisible"
      @close="Editdialogcloesd"
    >
      <!-- 主体 -->
      <el-form
        :model="edidFrom"
        :rules="EditFromRules"
        ref="editRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="edidFrom.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="edidFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="edidFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 这是底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      width="50%"
      title="分配角色"
      :visible.sync="SetRightsdialogVisible"
      @close="setRoledialogClose"
    >
      <!-- 主体 -->
      <div>
        <p>当前的用户：{{ userinfo.username }}</p>
        <p>当前的用户：{{ userinfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleid" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <!-- 这是底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    var chekEmail = (rule, value, cb) => {
      const regEmail =
        /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱！'))
    }
    var chekMobile = (rule, value, cb) => {
      const regmobile = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (regmobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号！'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      AdddialogVisible: false,
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: chekEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: chekMobile, trigger: 'blur' },
        ],
      },
      EditdialogVisible: false,
      edidFrom: {},
      EditFromRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: chekEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: chekMobile, trigger: 'blur' },
        ],
      },
      SetRightsdialogVisible: false,
      //用户信息
      userinfo: {},
      // 角色列表
      rolesList: [],
      selectRoleid:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 添加对话框关闭事件
    Adddialogcloesd() {
      this.$refs.addRef.resetFields()
    },
    AdddUser() {
      this.$refs.addRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addFrom)
        if (res.meta.status !== 200) {
          this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        this.AdddialogVisible = false
        this.getUserList()
      })
    },
    // 这是展示用户编辑的对话框
    async showEditdialog(id) {
      this.EditdialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户失败！')
      }
      this.edidFrom = res.data
    },
    Editdialogcloesd() {
      this.$refs.editRef.resetFields()
    },
    // 修改用户
    EditUser() {
      this.$refs.editRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.edidFrom.id,
          {
            email: this.edidFrom.email,
            mobile: this.edidFrom.mobile,
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error('修改用户失败！')
        }
        this.$message.success('修改用户成功！')
        this.getUserList()
        this.EditdialogVisible = false
      })
    },
    //删除用户
    async RemoveUser(id) {
      const confirmResult = await this.$confirm(
        '此操作将删除用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return his.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    //展示分配角色的对话框
    async setRole(userinfo) {
      this.userinfo = userinfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      this.SetRightsdialogVisible = true
    },
    // 分配角色事件
   async saveRoleInfo(){
      if(!this.selectRoleid){
        return this.$message.error('请选择角色！')
      }
      const {data:res} = await this.$http.put(`users/${this.userinfo.id}/role`,{
        rid:this.selectRoleid
      })
      if(res.meta.status!==200){
        return this.$message.error('更新角色失败！')

      }
      this.$message.success('添加角色成功！')
      this.SetRightsdialogVisible=false
      this.getUserList()
    },
    setRoledialogClose(){
      this.selectRoleid=''
      this.userinfo={}
    },
  },
}
</script>
<style  scoped>
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>